/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package deti.es.ukni.rest;

import deti.es.persistence.account.AccountDoesNotExist;
import deti.es.persistence.account.AccountManagerRemote;
import deti.es.ukni.cm.persistence.DAOFactory;
import deti.es.ukni.persistence.entity.Account;
import deti.es.ukni.persistence.entity.Band;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * RESTful Web Service - Account information.
 * <p>
 * This service returns the information of an
 * account. The requested account is identified
 * by it's name. If the account with <em>name</em>
 * exists a JSON object is returned with account's
 * information.
 * 
 * The information returned is the name, the bands
 * that he follows and, if the account has a band, the band
 * name and id. A empty object is return if account with name
 * <em>name</em> does not exist.
 *
 * @author ukni
 */

@Path("/account/{name}")
public class AccountsResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of AccountsResource */
    public AccountsResource() {
    }

    /**
     * Retrieves representation of an account.
     * 
     * @return JSON object with account information.
     */
    @GET
    @Produces("text/plain")
    public String getJson( @PathParam("name") String username ) {

        JSONObject json = new JSONObject();
        JSONArray  follow = new JSONArray();

        Account account;
        AccountManagerRemote AMBean;
        AMBean = DAOFactory.getAccountManager();
        try {
             account = AMBean.findAccount(username);

        } catch (AccountDoesNotExist ex) {
            return json.toJSONString();
        }

        json.put("username", account.getUsername() );
        for( Band b: account.getBandCollection() ){
            JSONObject jsonband = new JSONObject();
            jsonband.put("name", b.getName());
            jsonband.put("id", b.getIdband());

            follow.add( jsonband );
        }

        json.put("follow", follow);

        return json.toJSONString();
    }
}
